package com.pa.chong.pachong.tool.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;

@Component
public class DownloadImage {  

    @Autowired
    private QiNiuInput qiNiuInput ;



    public  void uploadToQiNiu(String urlString,String title,String imgType,String parentId,boolean flag) throws Exception {

        // 构造URL
        URL url = new URL(urlString);  
        // 打开连接  
        URLConnection con = url.openConnection();  
        
        //设置请求超时为5s  
        con.setConnectTimeout(5*100000000);
        String referer = url.getProtocol()+"://"+url.getHost();
        con.setRequestProperty("Referer", referer);

        // 输入流  
        InputStream is = con.getInputStream();
        byte[] byt = getStreamBytes(is);
        is.read(byt);


        qiNiuInput.upload(byt,title,imgType,parentId,flag);
        is.close();
    }


    public  void downloadDrect(String urlString, String savePath) throws Exception {

        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();

        //设置请求超时为5s
        con.setConnectTimeout(5*100000000);
        String referer = url.getProtocol()+"://"+url.getHost();
        con.setRequestProperty("Referer", referer);
        // 输入流
        InputStream is = con.getInputStream();
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        File sf=new File(savePath);
        if(!sf.exists()){
            sf.mkdirs();
        }
        String fileName = UUID.randomUUID().toString().replace("-","");
        OutputStream os = new FileOutputStream(sf.getPath()+"/"+fileName+".jpg");
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);

        }
        System.out.println("下载完成——————————————————————————————————>>>>");
        os.close();
        is.close();
    }


    public static byte[] getStreamBytes(InputStream is) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        byte[] b = baos.toByteArray();

        return b;
    }

}  
